package com.fzdy.dataplatform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzdy.dataplatform.controller.api.DelArr;
import com.fzdy.dataplatform.controller.api.ModuleCallback;
import com.fzdy.dataplatform.controller.api.business.BusinessListApi;
import com.fzdy.dataplatform.controller.api.sysLog.LogStringUtil;
import com.fzdy.dataplatform.controller.api.sysLog.SysLogApi;
import com.fzdy.dataplatform.core.common.AjaxCallback;
import com.fzdy.dataplatform.core.common.Check;
import com.fzdy.dataplatform.core.common.TimeStampTool;
import com.fzdy.dataplatform.core.controller.BaseController;
import com.fzdy.dataplatform.core.vo.Page;
import com.fzdy.dataplatform.entity.*;
import com.fzdy.dataplatform.service.AppService;
import com.fzdy.dataplatform.service.BusinessService;
import com.fzdy.dataplatform.service.KTVGroupService;
import com.fzdy.dataplatform.service.UserKtvBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/sysmanage/business")
public class BusinessController extends BaseController {

    @Autowired
    private BusinessService businessService;
    @Autowired
    private KTVGroupService ktvGroupService;
    @Autowired
    private UserKtvBusinessService userKtvBusinessService;
    @Autowired
    private AppService appService;


    @RequestMapping(value = "/list")
    public String list(@RequestBody Page<Business> page, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        Business business = new Business();
        business.setName(page.getName());
        if (!webUtilify.isAdmin(request)) {
            business.setUserid(webUtilify.LoginUserinfo(request).getId());
        } else {
            if (!Check.checkStringNull(page.getUname())) {
                User searchUser = new User(page.getUname());
                business.setUser(searchUser);
            }
        }
        business.setStatus(1);
        businessService.getPageByExampleLike(business, page);
        ajaxCallback = new AjaxCallback(Businessdbtoapi(page.getList(), webUtilify.isAdmin(request)), page.getTotalRow());
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getProtocolList")
    public String getProtocolList(@RequestBody BusinessListApi api, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        KTVGroup ktvGroup = new KTVGroup();
        if (webUtilify.isAdmin(request)) {
            if (api.getId() == null) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "参数错误");
                return JSON.toJSONString(ajaxCallback);
            } else {
                Business business = businessService.get(api.getId());
                ktvGroup.setUserid(business.getUserid());
            }
        } else {
            ktvGroup.setUserid(webUtilify.LoginUserinfo(request).getId());
        }
        List<KTVGroup> list = ktvGroupService.findByExampleEq(ktvGroup);
        List<BusinessListApi> apis = new ArrayList<>();
        for (KTVGroup ktv : list) {
            BusinessListApi api1 = new BusinessListApi(ktv.getId(), ktv.getName());
            apis.add(api1);
        }
        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "请求成功");
        ajaxCallback.setList(apis);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getAppList")
    public String getAppList(@RequestBody BusinessListApi api, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        App app=new App();
        if (webUtilify.isAdmin(request)) {
            if (api.getId() == null) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "参数错误");
                return JSON.toJSONString(ajaxCallback);
            } else {
                Business business = businessService.get(api.getId());
                app.setUserid(business.getUserid());
            }
        } else {
            app.setUserid(webUtilify.LoginUserinfo(request).getId());
        }
        app.setStatus(1);
        List<App> list = appService.findByExampleEq(app);
        List<BusinessListApi> apis = new ArrayList<>();
        for (App appapi : list) {
            BusinessListApi api1 = new BusinessListApi(appapi.getId(), appapi.getAppname());
            apis.add(api1);
        }
        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "请求成功");
        ajaxCallback.setList(apis);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/edit")
    public String edit(@RequestBody BusinessListApi api, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        User user = webUtilify.LoginUserinfo(request);
        /** 日志*/
        SysLogApi log_sysLogApi = new SysLogApi(LogStringUtil.BUSINESS, LogStringUtil.SUCCESS, user.getId());
        JSONObject log_content = new JSONObject();
        if (api.getId() != null) {
            /** 修改 **/
            log_sysLogApi.setOperation(LogStringUtil.UPDATA);
            Business business = businessService.get(api.getId());
            log_content.put(LogStringUtil.BEFOREEDIT,  business.toString());
            if (business == null || business.getStatus().equals(0)) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "找不到对应业务");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put(LogStringUtil.CAUSEFAIL, "找不到对应业务");
            } else if (!webUtilify.isAdmin(request) && !business.getUserid().equals(user.getId())) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "找不到对应业务");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put(LogStringUtil.CAUSEFAIL, "找不到对应业务");
            } else {
                business.setMemo(api.getMemo());
                business.setName(api.getName());
                business.setAppid(api.getAppid());
                business.setProductid(api.getProductid());
                log_content.put(LogStringUtil.AFTEREDIT, business.toString());
                businessService.updateT(business);
                List<UserKtvBusiness> list = userKtvBusinessService.findByExampleEq(new UserKtvBusiness(business.getId()));
                if (api.getProtocolid() != null) {
                    if (list.size() == 0) {
                        UserKtvBusiness userKtvBusiness = new UserKtvBusiness(api.getId(), api.getProtocolid(), api.getMemo());
                        userKtvBusinessService.insertT(userKtvBusiness);
                    } else {

                        UserKtvBusiness userKtvBusiness = list.get(0);
                        userKtvBusiness.setMemo(api.getMemo());
                        userKtvBusiness.setKtvgroupid(api.getProtocolid());
                        userKtvBusinessService.updateT(userKtvBusiness);
                    }
                } else {
                    if (list.size() != 0) {
                        userKtvBusinessService.deleteByIdT(list.get(0).getId());
                    }
                }
                ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "修改成功");
            }
        } else {
            /** 添加 **/
            log_sysLogApi.setOperation(LogStringUtil.ADD);
            if (api.getKey() == null || api.getKey().length() != 32) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "key值不正确");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put(LogStringUtil.CAUSEFAIL, "key值不正确");
            } else if (webUtilify.isAdmin(request)) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "参数错误");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put(LogStringUtil.CAUSEFAIL, "参数错误");
            } else {
                Business business = new Business(api.getName(), api.getMemo(),
                        webUtilify.LoginUserinfo(request).getId(), api.getProductid(), api.getKey());
                business.setAppid(api.getAppid());
                Serializable id = businessService.insertT(business);
                log_content.put("业务信息",  business.toString());
                if (api.getProtocolid() != null) {
                    UserKtvBusiness userKtvBusiness = new UserKtvBusiness((Integer) id, api.getProtocolid(), api.getMemo());
                    userKtvBusinessService.insertT(userKtvBusiness);
                }
                ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "添加成功");
            }
        }
        log_sysLogApi.setContent(log_content);
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }


    @RequestMapping(value = "/getBusiness")
    public String getBusiness(@RequestBody Business business, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        business = businessService.get(business.getId());
        if (business == null || business.getStatus().equals(0)) {
            ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "找不到对应业务");
            return JSON.toJSONString(ajaxCallback);
        }
        if (business.getUserid().equals(webUtilify.LoginUserinfo(request).getId()) || webUtilify.isAdmin(request)) {
            UserKtvBusiness userKtvBusiness = new UserKtvBusiness();
            userKtvBusiness.setBusinessid(business.getId());
            List<UserKtvBusiness> list = userKtvBusinessService.findByExampleEq(userKtvBusiness);
            BusinessListApi api = new BusinessListApi(business.getId(), business.getName(), business.getMemo());

            if (business.getApp()!=null&&(business.getApp().getStatus()!=0)){
                api.setAppid(business.getAppid());
                api.setApp(business.getApp().getAppname());
                api.setPushurl(business.getApp().getPushaddress());
            }
            api.setProductid(business.getProductid());
            if (business.getProductid() != null) {
                api.setProductname(business.getProduct().getName());
            }
            api.setKey(business.getKey());
            if (list.size() != 0) {
                api.setProtocolid(list.get(0).getKtvgroupid());
                if (list.get(0).getKtvGroup() != null)
                    api.setProtocolName(list.get(0).getKtvGroup().getName());
            }
            ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "请求成功");
            ajaxCallback.setData(api);
        } else {
            ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "找不到对应业务");
        }

        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/del")
    public String del(@RequestBody DelArr arr, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        JSONObject log_content = new JSONObject();
        businessService.batchDelete(arr.getIds());
        log_content.put("id", JSON.toJSONString(arr.getIds()));
        syslogService.WriteLog(new SysLogApi(LogStringUtil.DEL, LogStringUtil.BUSINESS, LogStringUtil.SUCCESS,
                log_content, webUtilify.LoginUserinfo(request).getId()));
        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "删除成功");
        return JSON.toJSONString(ajaxCallback);
    }

    private List Businessdbtoapi(List<Business> list, Boolean isadmin) {
        List<BusinessListApi> apis = new ArrayList<>();
        for (Business business : list) {
            BusinessListApi api = new BusinessListApi(business.getId(), business.getName(), business.getUser().getName(),
                    business.getMemo(), TimeStampTool.DateToString("yy-MM-dd HH:mm:ss", business.getCreatedate()));
            if (business.getApp()!=null&&(business.getApp().getStatus()!=0)){
                api.setApp(business.getApp().getAppname());
                api.setPushurl(business.getApp().getPushaddress());
            }
            if (!isadmin) {
                api.setUname(null);
            }
            apis.add(api);
        }
        return apis;
    }
}
